package com.android.infantschool.ui.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.ClockingBaseBean;
import com.android.infantschool.bean.ResponseBean;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.mvp.presenter.ClockBasePresenter;
import com.android.infantschool.model.mvp.presenter.ClockBasePresenterImpl;
import com.android.infantschool.model.mvp.presenter.ClockSignOutPresenter;
import com.android.infantschool.model.mvp.presenter.ClockSignOutPresenterImpl;
import com.android.infantschool.model.mvp.view.ClockBaseView;
import com.android.infantschool.model.mvp.view.ClockSignOutView;
import com.android.infantschool.ui.activity.BabyInfoActivity;
import com.android.infantschool.ui.activity.BabyThermometryActivity;
import com.android.infantschool.ui.activity.LoginActivity;
import com.android.infantschool.ui.activity.MainActivity;
import com.android.infantschool.ui.activity.SetUpActivity;
import com.android.infantschool.ui.adapter.ClockingBaseAdapter;
import com.android.infantschool.ui.dialog.CommomDialog;
import com.android.infantschool.ui.dialog.DialogSearchBle;
import com.android.infantschool.util.DateUtil;
import com.android.infantschool.util.LocationUtil;
import com.android.infantschool.util.ToastUtil;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Administrator
 * @particulars
 * @time 2019\7\3 0003 17:21
 * @class describe 选项卡显示签到模块
 */
public class ClockingSignInFragment extends BaseFragment implements View.OnClickListener, ClockingBaseAdapter.OnLister, ClockBaseView, ClockSignOutView {

    private Button btnSignIn;
    private Button btnSignOut;
    private TextView tvSelectTime;
    private RelativeLayout rlTitle;
    private TextView tvNotSignIn;
    private TextView tvYesSignIn;
    private TextView tvLeaveIn;
    private LinearLayout lyTitleSignIn;
    private TextView tvNotSignOut;
    private TextView tvYesSignOut;
    private LinearLayout lyTitleSignOut;
    private RecyclerView recyclerView;

    private ClockingBaseAdapter clockingBaseAdapter;
    private int TYPE_LAYOUT = 1;//1:未签到,2:已签到,3:请假,4:未签退,5:已签退

    /**
     * 取得默认的蓝牙适配器
     */
    private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    /**
     * 连接到的蓝牙设备
     */
    private Map<String, String> mapDevice = new HashMap<>();
    private DialogSearchBle dialogSearchBle;

    private ClockBasePresenter basePresenter = null;
    private ClockSignOutPresenter outPresenter = null;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chocking_sign_in, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume...");
        if (TYPE_LAYOUT == 1) {
            Log.e(TAG, "当前显示未签到栏目");
            showNotSignIn();
        } else {
            Log.e(TAG, "当前未显示未签到栏目");
        }
    }

    private void initView(View view) {
        basePresenter = new ClockBasePresenterImpl(this);
        outPresenter = new ClockSignOutPresenterImpl(this);
        btnSignIn = (Button) view.findViewById(R.id.btn_sign_in);
        btnSignIn.setOnClickListener(this);
        btnSignOut = (Button) view.findViewById(R.id.btn_sign_out);
        btnSignOut.setOnClickListener(this);
        tvSelectTime = (TextView) view.findViewById(R.id.tv_select_time);
        tvSelectTime.setOnClickListener(this);
        rlTitle = (RelativeLayout) view.findViewById(R.id.rl_title);
        rlTitle.setOnClickListener(this);
        tvNotSignIn = (TextView) view.findViewById(R.id.tv_not_sign_in);
        tvNotSignIn.setOnClickListener(this);
        tvYesSignIn = (TextView) view.findViewById(R.id.tv_yes_sign_in);
        tvYesSignIn.setOnClickListener(this);
        tvLeaveIn = (TextView) view.findViewById(R.id.tv_leave_in);
        tvLeaveIn.setOnClickListener(this);
        lyTitleSignIn = (LinearLayout) view.findViewById(R.id.ly_title_sign_in);
        lyTitleSignIn.setOnClickListener(this);
        tvNotSignOut = (TextView) view.findViewById(R.id.tv_not_sign_out);
        tvNotSignOut.setOnClickListener(this);
        tvYesSignOut = (TextView) view.findViewById(R.id.tv_yes_sign_out);
        tvYesSignOut.setOnClickListener(this);
        lyTitleSignOut = (LinearLayout) view.findViewById(R.id.ly_title_sign_out);
        lyTitleSignOut.setOnClickListener(this);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setOnClickListener(this);

        recyclerView.setLayoutManager(new GridLayoutManager(activity, 4));
        clockingBaseAdapter = new ClockingBaseAdapter(activity, this);
        recyclerView.setAdapter(clockingBaseAdapter);

        tvSelectTime.setText(DateUtil.getDate(DateUtil.ymd));
        registerReceiver();
        showSignIn();

        boolean isStart = mBtAdapter.startDiscovery();
        Log.e(TAG, " 开始搜索蓝牙状态:" + isStart);
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                Log.e(TAG, "初始化完成,当前扫描到的设备:" +
                        device.getName() + "," + device.getAddress());
                if (mapDevice.containsKey("BF4030")) {
                    if (mapDevice.get("BF4030").startsWith("0F:03")) {
                        dismissSerrchBle();
                        ToastUtil.showShortToast(activity, "搜索成功");
                        break;
                    }
                } else {
                    mapDevice.put(device.getName(), device.getAddress());
                }
            }
        } else {
            Log.e(TAG, "初始化完成,没有搜索到设备");
        }
    }

    public void registerReceiver() {
        IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        discoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        activity.registerReceiver(mReceiver, discoveryFilter);
    }

    private void getBabyInfo(int type) {
        this.showLoading();
        clockingBaseAdapter.clear();
        TYPE_LAYOUT = type;
        Map<String, String> map = new HashMap<>();
        map.put("token", AppConfig.getToken());
        map.put("day", tvSelectTime.getText().toString());
        map.put("type", String.valueOf(type));
        Log.e(TAG, "map:" + map.toString());
        basePresenter.getClockBase(map);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                if (!mapDevice.containsKey(device.getName())) {
                    if (device.getName() == null || device.getAddress() == null) {
                        return;
                    }
                    if (device.getName().equals("BF4030") && device.getAddress().startsWith("0F:04")) {
                        return;
                    }

                    if (mapDevice.containsKey("BF4030")) {
                        dismissSerrchBle();
                        ToastUtil.showShortToast(activity, "搜索成功");
                        return;
                    }

                    if (mapDevice.containsKey("BF4030")) {
                        if (mapDevice.get("BF4030").startsWith("0F:03")) {
                            dismissSerrchBle();
                            ToastUtil.showShortToast(activity, "搜索成功");
                            return;
                        }
                    }

                    int a2dp = mBtAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
                    int headset = mBtAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
                    int health = mBtAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);
                    int flag = -1;
                    if (a2dp == BluetoothProfile.STATE_CONNECTED) {
                        flag = a2dp;
                    } else if (headset == BluetoothProfile.STATE_CONNECTED) {
                        flag = headset;
                    } else if (health == BluetoothProfile.STATE_CONNECTED) {
                        flag = health;
                    }
                    if (flag != -1) {
                        mBtAdapter.getProfileProxy(activity, new BluetoothProfile.ServiceListener() {
                            @Override
                            public void onServiceDisconnected(int profile) {
                                // TODO Auto-generated method stub
                            }

                            @Override
                            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                                // TODO Auto-generated method stub
                                List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
                                if (mDevices != null && mDevices.size() > 0) {
                                    for (BluetoothDevice device : mDevices) {
                                        Log.e(TAG, "device name: " + device.getName() + "," + device.getAddress());
                                    }
                                } else {
                                    Log.e(TAG, "mDevices is null");
                                }
                            }
                        }, flag);
                    } else {

                    }
                    Log.e(TAG, "搜索到的蓝牙设备:" + device.getName() + "," + device.getAddress());
                    mapDevice.put(device.getName(), device.getAddress());
                    if (device.getName().equals("BF4030") && device.getAddress().startsWith("0F:03")) {
                        dismissSerrchBle();
                        ToastUtil.showShortToast(activity, "搜索成功");
                    }
                }
                //}
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                activity.setProgressBarIndeterminateVisibility(false);
                Log.e(TAG, "未搜索到蓝牙设备");
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // If BT is not on, request that it be enabled.
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e(TAG, "onStart...");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3 && resultCode == Activity.RESULT_OK) {
            Log.e(TAG, "蓝牙授权成功");
            showSearchBle();
            if (mBtAdapter.isDiscovering()) {
                boolean isCancel = mBtAdapter.cancelDiscovery();
                Log.e(TAG, " 取消搜索蓝牙状态:" + isCancel);
            }
            boolean isStart = mBtAdapter.startDiscovery();
            Log.e(TAG, " 开始搜索蓝牙状态:" + isStart);
        }
        if (requestCode == 4 && resultCode == Activity.RESULT_OK) {
            Log.e(TAG, "位置服务已打开");
            if (!mBtAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, 3);
                return;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }
        if (basePresenter != null) {
            basePresenter.onDestroy();
            basePresenter = null;
        }
        if (outPresenter != null) {
            outPresenter.onDestroy();
            outPresenter = null;
        }
        mapDevice.clear();
        if (mReceiver != null) {
            activity.unregisterReceiver(mReceiver);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sign_in:      //签到
                showSignIn();
                break;
            case R.id.btn_sign_out:     //签退
                showSignOut();
                break;
            case R.id.tv_not_sign_in:   //未签到
                showNotSignIn();
                break;
            case R.id.tv_yes_sign_in:   //已签到
                showYesSignIn();
                break;
            case R.id.tv_leave_in:      //请假
                showLeaveIn();
                break;
            case R.id.tv_not_sign_out:  //未签退
                showNotSignOut();
                break;
            case R.id.tv_yes_sign_out:  //已签退
                showYesSignOut();
                break;
            case R.id.tv_select_time:   //选择时间
                showYearMonthPicker();
                break;
        }
    }

    private void showSearchBle() {
        if (dialogSearchBle != null) {
            dialogSearchBle.dismiss();
            dialogSearchBle = null;
        }
        dialogSearchBle = new DialogSearchBle(activity);
        dialogSearchBle.show();
    }

    private void dismissSerrchBle() {
        if (dialogSearchBle != null) {
            dialogSearchBle.dismiss();
            dialogSearchBle = null;
        }
    }

    /**
     * 年月日选择
     */
    private void showYearMonthPicker() {
        new TimePickerBuilder(activity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = formatter.format(date);
                tvSelectTime.setText(dateString);

                ClockingSignInFragment.this.showLoading();
                clockingBaseAdapter.clear();
                Map<String, String> map = new HashMap<>();
                map.put("token", AppConfig.getToken());
                map.put("day", dateString);
                map.put("type", String.valueOf(TYPE_LAYOUT));
                Log.e(TAG, "map:" + map.toString());
                basePresenter.getClockBase(map);
            }
        }).setSubmitColor(0xFF007C70).setCancelColor(0xFF999999).build().show();
    }

    @Override
    public void lister(final int position, int type) {
        switch (type) {
            case 1:
                if (mBtAdapter == null) {
                    ToastUtil.showShortToast(activity, "设备不支持蓝牙");
                    return;
                }

                if (!LocationUtil.isLocServiceEnable(activity)) {
                    LocationUtil.showGPSContacts(activity, 4);
                    return;
                }

                if (!mBtAdapter.isEnabled()) {
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, 3);
                    return;
                }

                if (mapDevice.containsKey("BF4030")) {
                    if (mBtAdapter.isDiscovering()) {
                        boolean isCancel = mBtAdapter.cancelDiscovery();
                        Log.e(TAG, " 取消搜索蓝牙状态:" + isCancel);
                    }
                    startActivity(BabyInfoActivity.newIntent(activity, "BF4030", mapDevice.get("BF4030"), clockingBaseAdapter.list.get(position).getName(), String.valueOf(clockingBaseAdapter.list.get(position).getId())));
                } else {
                    showSearchBle();
                    if (mBtAdapter.isDiscovering()) {
                        boolean isCancel = mBtAdapter.cancelDiscovery();
                        Log.e(TAG, " 取消搜索蓝牙状态:" + isCancel);
                    }
                    boolean isStart = mBtAdapter.startDiscovery();
                    Log.e(TAG, " 开始搜索蓝牙状态:" + isStart);
                }
                break;
            case 4://未签退
                new CommomDialog(activity, R.style.dialog_loading, "签退", new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            dialog.dismiss();
                            ClockingSignInFragment.this.showLoading();
                            Map<String, String> map = new HashMap<>();
                            map.put("token", AppConfig.getToken());
                            map.put("id", String.valueOf(clockingBaseAdapter.list.get(position).getId()));
                            outPresenter.postClockSignOut(map);
                        }
                    }
                }).setTitle("签退").show();
                break;
        }
    }

    @Override
    public void errorClockBase(String error) {
        this.dismissLoading();
        clockingBaseAdapter.clear();
        ToastUtil.showShortToast(activity, "网络异常:" + error);
    }

    @Override
    public void successClockBase(BaseBean baseBean) {
        this.dismissLoading();
        ClockingBaseBean clockingBaseBean = (ClockingBaseBean) baseBean;
        if (clockingBaseBean.getCode() == 0) {
            clockingBaseAdapter.setData(clockingBaseBean.getData(), TYPE_LAYOUT);
        } else {
            clockingBaseAdapter.clear();
            ToastUtil.showShortToast(activity, "获取失败:" + clockingBaseBean.getMsg());
        }
    }

    @Override
    public void errorClockSignOut(String error) {
        ClockingSignInFragment.this.dismissLoading();
        ToastUtil.showShortToast(activity, "网络异常:" + error);
    }

    @Override
    public void successClockSignOut(BaseBean baseBean) {
        ClockingSignInFragment.this.dismissLoading();
        ResponseBean responseBean = (ResponseBean) baseBean;
        if (responseBean.getCode() == 0) {
            ToastUtil.showShortToast(activity, "签到成功");
            ClockingSignInFragment.this.showLoading();
            getBabyInfo(4);
        } else {
            ToastUtil.showShortToast(activity, "签到失败:" + responseBean.getMsg());
        }
    }

    /**
     * 显示未签到栏目
     */
    private void showNotSignIn() {
        tvNotSignIn.setTextColor(0xFF007C70);
        tvYesSignIn.setTextColor(0xFF000000);
        tvLeaveIn.setTextColor(0xFF000000);
        getBabyInfo(1);
    }

    /**
     * 显示已签到栏目
     */
    private void showYesSignIn() {
        tvNotSignIn.setTextColor(0xFF000000);
        tvYesSignIn.setTextColor(0xFF007C70);
        tvLeaveIn.setTextColor(0xFF000000);
        getBabyInfo(2);
    }

    /**
     * 显示请假栏目
     */
    private void showLeaveIn() {
        tvNotSignIn.setTextColor(0xFF000000);
        tvYesSignIn.setTextColor(0xFF000000);
        tvLeaveIn.setTextColor(0xFF007C70);
        getBabyInfo(3);
    }

    /**
     * 显示未签退栏目
     */
    private void showNotSignOut() {
        tvNotSignOut.setTextColor(0xFF007C70);
        tvYesSignOut.setTextColor(0xFF000000);
        getBabyInfo(4);
    }

    /**
     * 显示已签退栏目
     */
    private void showYesSignOut() {
        tvYesSignOut.setTextColor(0xFF007C70);
        tvNotSignOut.setTextColor(0xFF000000);
        getBabyInfo(5);
    }

    /**
     * 签到栏目
     */
    private void showSignIn() {
        btnSignIn.setBackgroundResource(R.drawable.btn_green_left);
        btnSignOut.setBackgroundResource(R.drawable.btn_white_right);
        lyTitleSignIn.setVisibility(View.VISIBLE);
        lyTitleSignOut.setVisibility(View.GONE);
        btnSignIn.setTextColor(0xFFFFFFFF);
        btnSignOut.setTextColor(0xFF007C70);
        showNotSignIn();
    }

    /**
     * 签退栏目
     */
    private void showSignOut() {
        btnSignIn.setBackgroundResource(R.drawable.btn_white_left);
        btnSignOut.setBackgroundResource(R.drawable.btn_green_right);
        lyTitleSignIn.setVisibility(View.GONE);
        lyTitleSignOut.setVisibility(View.VISIBLE);
        btnSignOut.setTextColor(0xFFFFFFFF);
        btnSignIn.setTextColor(0xFF007C70);
        showNotSignOut();
    }

}